<template>
  <div id='Params'>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="注意:只允许为第三级分类设置相关的参数" type="warning" show-icon :closable="false">
      </el-alert>
      <el-row class="row_opt">
        <el-col>
          <span>选择商品分类:</span>
          <el-cascader :options="cateList" v-model="selectCateKeys"
            :props="{ expandTrigger: 'hover', value: 'cat_id', label: 'cat_name', children: 'children' }"
            @change="cateHandleChange" size="mini">
          </el-cascader>
        </el-col>
      </el-row>
      <!-- tab页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 动态参数 -->
        <el-tab-pane label="动态参数" name="many" :disabled="btnDisable">
          <el-button class="btnOne" size="mini" type="primary" :disabled="btnDisable" @click="addParameter">添加参数
          </el-button>
          <el-table :data="manyOnlyData" border stripe size="mini">
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag :key="i" v-for="(tag, i) in scope.row.attr_vals" closable disable-transitions
                  @close="closeTag(tag, scope.row)" class="tagipt">
                  {{ tag }}
                </el-tag>
                <el-input class="tagipt input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                  ref="saveTagInput" size="small" @keyup.enter.native="$event.target.blur()"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button class="tagipt button-new-tag" v-else size="small" @click="showInput(scope.row)">+ New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="editParams(scope.row)">编辑</el-button>
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="openDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性 -->
        <el-tab-pane label="静态属性" name="only" :disabled="btnDisable">
          <el-button class="btnOne" size="mini" type="primary" :disabled="btnDisable" @click="addattribute">添加属性
          </el-button>
          <el-table :data="manyOnlyData" border stripe size="mini">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag :key="i" v-for="(tag, i) in scope.row.attr_vals" closable disable-transitions
                  @close="closeTag(tag, scope.row)" class="tagipt">
                  {{ tag }}
                </el-tag>
                <el-input class="tagipt input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                  ref="saveTagInput" size="small" @keyup.enter.native="$event.target.blur()"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button class="tagipt button-new-tag" v-else size="small" @click="showInput(scope.row)">+ New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- {{ scope.row  }} -->
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="editAttribute(scope.row)">编辑
                </el-button>
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="openDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数的对话框 -->
    <el-dialog :title="'添加' + titleText" :visible.sync="addParamsDialogVisible" width="30%" @close="clearIpt">
      <!-- 表单验证区域 -->
      <el-form :model="addRuleForm" :rules="addRules" ref="addRuleFormRef" label-width="80px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addRuleForm.attr_name" size="mini"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureSubParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数的对话框 -->
    <el-dialog :title="'修改' + titleText" :visible.sync="editParamsDialogVisible" width="30%" @close="clearEditParams">
      <el-form :model="editParamsForm" ref="editRuleFormRef" label-width="100px">
        <el-form-item :label="'修改' + titleText">
          <el-input v-model="editRuleForm.attr_name" size="mini"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureEditParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Params',
  created() {
    this.getCateList()
  },
  computed: {
    btnDisable() {
      if (this.selectCateKeys.length !== 3) {
        return true
      }
      return false
    },
    cateId() {
      if (this.selectCateKeys.length === 3) {
        return this.selectCateKeys[2]
      }
      return null
    },
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  },
  data() {
    return {
      // inputVisible: false,
      // inputValue: '',
      editParamsDialogVisible: false,
      editParamsForm: [],
      cateList: [],
      selectCateKeys: [],
      activeName: 'many',
      manyOnlyData: [],
      addParamsDialogVisible: false,
      addRuleForm: {
        attr_name: ''
      },
      editRuleForm: {
        attr_name: ''
      },
      // 验证方式区域
      addRules: {
        attr_name: [
          { required: true, message: '请输入添加名称', trigger: 'blur' },
          { min: 1, message: '长度在 1 个字符以上', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    openDelete(val) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { attr_id } = val
        const { meta } = await this.$http.delete(`categories/${this.cateId}/attributes/${attr_id}`)
        if (meta.status !== 200) return this.$message.error('删除失败')
        this.getAttributes()
        this.$message.success('删除成功!')
      }).catch(() => {
        this.$message('取消删除成功')
      })
    },
    async sureEditParams() {
      const { attr_id, attr_sel } = this.editParamsForm
      const { data, meta } = await this.$http.put(`categories/${this.cateId}/attributes/${attr_id}`, { attr_name: this.editRuleForm.attr_name, attr_sel })
      if (meta.status !== 200) return this.$message.error('数据提交失败')
      this.getAttributes()
      this.$message.success(data.attr_name + '数据更新成功')
      this.editParamsDialogVisible = false
    },
    clearEditParams() {
      this.$refs.editRuleFormRef.resetFields()
    },
    editParams(val) {
      this.editParamsForm = val
      this.editRuleForm.attr_name = this.editParamsForm.attr_name
      this.editParamsDialogVisible = true
    },
    editAttribute(val) {
      this.editParamsForm = val
      this.editRuleForm.attr_name = this.editParamsForm.attr_name
      this.editParamsDialogVisible = true
    },
    sureSubParams() {
      this.$refs.addRuleFormRef.validate(async (valid) => {
        if (!valid) return
        const { data, meta } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addRuleForm.attr_name,
          attr_sel: this.activeName
        })
        if (meta.status !== 201) return this.$message.error('提交数据失败')
        this.getAttributes()
        this.$message.success(data.attr_name + '添加成功')
        this.addParamsDialogVisible = false
      })
    },
    clearIpt() {
      this.addRuleForm.attr_name = ''
      this.$refs.addRuleFormRef.resetFields()
    },
    addParameter() {
      this.addParamsDialogVisible = true
    },
    addattribute() {
      this.addParamsDialogVisible = true
    },
    async getCateList() {
      const { data, meta } = await this.$http.get('categories')
      if (meta.status !== 200) return this.$message.error('获取商品分类数据失败')
      this.cateList = data
    },
    cateHandleChange() {
      if (this.selectCateKeys.length !== 3) {
        this.$message('该商品分类不是第三级分类,无法设置相关的参数')
        this.selectCateKeys = []
        this.manyOnlyData = []
        return
      }
      console.log(this.selectCateKeys)
      this.getAttributes()
    },
    handleTabClick() {
      console.log(this.activeName)
      this.getAttributes()
    },
    // 获取分类参数数据
    async getAttributes() {
      const { data, meta } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
      console.log(data)
      if (meta.status !== 200) return this.$message.error('分类参数数据获取失败')
      this.dealData(data)
      this.manyOnlyData = data
      console.log(this.manyOnlyData)
    },

    dealData(data) {
      data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      return data
    },
    // attr_id: 3077
    // attr_name: "版式"
    // attr_sel: "many"
    // attr_vals: Array(4)

    async closeTag(tag, row) {
      const { attr_id: id, attr_name, attr_sel, attr_vals: arr } = row
      arr.splice(arr.indexOf(tag), 1)
      const { meta } = await this.$http.put(`categories/${this.cateId}/attributes/${id}`, { attr_name, attr_sel, attr_vals: arr.join(' ') })
      if (meta.status !== 200) return this.$message.error(meta.msg)
      this.$message.success('删除成功')
    },
    async handleInputConfirm(val) {
      let { attr_id: id, attr_name, attr_sel, attr_vals: arr, inputValue } = val
      if (inputValue.trim().length === 0) {
        inputValue = ''
        val.inputVisible = false
        console.log('返回')
        return
      }
      arr.push(inputValue.trim())
      val.inputVisible = false
      inputValue = ''
      console.log('handleInputConfirm', arr)
      const { meta } = await this.$http.put(`categories/${this.cateId}/attributes/${id}`, { attr_name, attr_sel, attr_vals: arr.join(' ') })
      console.log(attr_name, attr_sel, arr)
      if (meta.status !== 200) return this.$message.error(meta.msg)
      this.$message.success('添加成功')
      val.inputValue = ''
    },
    showInput(val) {
      val.inputVisible = true
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
      console.log('showInput')
    }
  }
}
</script>

<style lang="less" scoped>
.row_opt {
  padding-left: 10px;
  margin: 10px 0;

  span {
    margin-right: 10px;
  }
}

.btnOne {
  margin-bottom: 10px;
}

/deep/.el-table .el-table__cell {
  text-align: center;
}

.tagipt {
  margin: 0 10px;
}

.el-tag+.el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
